package com.yanq.liancar.activity;
/*
 *  @创建者     李岩
 *  @创建时间   2018/10/8  14:30
 *  @描述       ${TODO}
 */


import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.ScaleAnimation;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.bean.ShopByPrecisionBean;
import com.yanq.liancar.bean.ShopListBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


public class PeripheralShopActivity extends BaseToolbarActivity implements AMap.OnMarkerClickListener {

    @BindView(R.id.mapview)
    MapView mapview;
    @BindView(R.id.img_logo)
    ImageView imgLogo;
    @BindView(R.id.shop_title)
    TextView shopTitle;
    @BindView(R.id.shop_address)
    TextView shopAddress;
    @BindView(R.id.tv_shopaddress)
    TextView tvShopaddress;
    @BindView(R.id.tv_shoppinglun)
    TextView tvShoppinglun;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.ll_shopdetails)
    LinearLayout llShopdetails;
    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    private AMapLocationClientOption mLocationOption = null;
    private double Latitude, Longitude;
    private int page = 1;
    private int type;
    private List<ShopListBean.DataBean> shopListBeanList = new ArrayList<>();
    private AMap mAMap;
    //定义一个UiSettings对象
    private UiSettings mUiSettings;
    private Marker marker;
    private LatLng markerPosition;
    private MyLocationStyle myLocationStyle;
    private List<LatLng> pointList = new ArrayList<LatLng>();
    private ArrayList<Marker> mMarkers = new ArrayList<Marker>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_peripheralshop);
        Utils.setStatusBar(this, true, false);
        ButterKnife.bind(this);
        mTvTitle.setText("周围店铺");
        type = getIntent().getExtras().getInt("type");
        mapview.onCreate(savedInstanceState);
        init();
        getLocation();

    }

    private void getLocation() {
        mLocationClient = new AMapLocationClient(this);
        mLocationOption = new AMapLocationClientOption();
        //        /**
        //         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
        //         */
        //        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        //        if(null != mLocationClient){
        //            mLocationClient.setLocationOption(mLocationOption);
        //            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
        //            mLocationClient.stopLocation();
        //            mLocationClient.startLocation();
        //        }
        myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW_NO_CENTER);//连续定位、蓝点不会移动到地图中心点，并且蓝点会跟随设备移动。
        mAMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        mAMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果
        mLocationOption.setOnceLocation(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        Latitude = aMapLocation.getLatitude();//获取纬度
                        Longitude = aMapLocation.getLongitude();//获取经度
                        LogUtils.e("经纬度====", Latitude + "=======" + Longitude);
                        if (type == 1) {
                            initOkGoAddService1();
                        } else {
                            initOkGoAddService();
                        }
                        markerPosition = new LatLng(Latitude, Longitude);
                        mAMap.moveCamera(CameraUpdateFactory.changeLatLng(markerPosition));
                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        });

    }

    /**
     * 初始化AMap对象
     */

    private void init() {

        if (mAMap == null) {
            mAMap = mapview.getMap();
            mUiSettings = mAMap.getUiSettings();
            mUiSettings.setZoomControlsEnabled(false);  //显示缩放按钮
            mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);
            mAMap.moveCamera(CameraUpdateFactory.zoomTo(12));
            mAMap.setOnMarkerClickListener(this);
        }

        // addGrowMarker();

    }

    /**
     * 添加带生长效果marker
     */

    private void addGrowMarker() {

        MarkerOptions options = new MarkerOptions();

        options.position(markerPosition);

        options.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.icon_openmap_mark)));

        marker = mAMap.addMarker(options);

        Animation markerAnimation = new ScaleAnimation(0, 1, 0, 1); //初始化生长效果动画

        markerAnimation.setDuration(1000);  //设置动画时间 单位毫秒

        marker.setAnimation(markerAnimation);


    }

    //查询普通店铺列表
    private void initOkGoAddService() {
        OkGo.<String>post(Config.s + "llc/shop/queryShopByType")
                .tag(this)
                .params("serviceType", type)
                .params("page", page)
                .params("num", 1000)
                .params("lat", Latitude)
                .params("lon", Longitude)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        ShopListBean baseBean = gson.fromJson(response.body(), ShopListBean.class);
                        if (baseBean.isIsSuccess()) {
                            shopListBeanList.clear();
                            shopListBeanList.addAll(baseBean.getData());
                            for (int i = 0; i < shopListBeanList.size(); i++) {
                                pointList.add(new LatLng(shopListBeanList.get(i).getLat(), shopListBeanList.get(i).getLon()));

                                Marker marker = mAMap.addMarker(new MarkerOptions().position(pointList.get(i))

                                        .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_openmap_mark))));
                                Animation markerAnimation = new ScaleAnimation(0, 1, 0, 1); //初始化生长效果动画

                                markerAnimation.setDuration(1000);  //设置动画时间 单位毫秒

                                marker.setAnimation(markerAnimation);
                                marker.setObject(pointList.size() - 1);

                                mMarkers.add(marker);
                            }

                        } else {
                            RxToast.error(baseBean.getOutputMessage());
                        }
                    }
                });
    }

    //查询精致洗车店铺列表
    private void initOkGoAddService1() {
        OkGo.<String>post(Config.s + "llc/fineCarServerController/queryShopForFCWServerList")
                .tag(this)
                .params("page", page)
                .params("num", 1000)
                .params("lat", Latitude)
                .params("lon", Longitude)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        ShopListBean baseBean = gson.fromJson(response.body(), ShopListBean.class);
                        if (baseBean.isIsSuccess()) {

                            shopListBeanList.clear();

                            shopListBeanList.addAll(baseBean.getData());

                        } else {
                            RxToast.error(baseBean.getOutputMessage());
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient.onDestroy();
            mLocationClient = null;
            mLocationOption = null;
        }

        for (Marker mark : mMarkers) {
            mark.remove();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        mapview.onResume();
        // marker.startAnimation();
    }


    @Override
    protected void onPause() {
        super.onPause();
        mapview.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        mapview.onSaveInstanceState(outState);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        marker.startAnimation();
        double lat = marker.getOptions().getPosition().latitude;
        double lon = marker.getOptions().getPosition().longitude;
        getShopMessage(lat,lon);
        return true;
    }

    private void getShopMessage(double lat ,double lon){
        OkGo.<String>post(Config.s + "llc/shop/queryShopByPrecision")
                .tag(this)
                .params("lat", lat)
                .params("lon", lon)
                .params("lat1", Latitude)
                .params("lon1", Longitude)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        ShopByPrecisionBean baseBean = gson.fromJson(response.body(), ShopByPrecisionBean.class);
                        if (baseBean.isIsSuccess()) {
                            llShopdetails.setVisibility(View.VISIBLE);
                            RequestOptions options=new RequestOptions();
                            options.error(R.mipmap.item_fuwu);
                            Glide.with(mContext).load(baseBean.getData().getShopPage()).apply(options).into(imgLogo);
                            shopTitle.setText(baseBean.getData().getShopName());
                            shopAddress.setText(baseBean.getData().getShopAddress());
                            tvShopaddress.setText( new BigDecimal(baseBean.getData().getLang()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "Km");
                            tvShoppinglun.setText(baseBean.getData().getRamarkNum()+"");
                            text.setText(baseBean.getData().getAttenNum()+"");
                        } else {
                            RxToast.error(baseBean.getOutputMessage());
                        }
                    }
                });
    }
}
